package logic

import (
	"context"
	"fmt"
	"strconv"
	"usershop/api/internal/svc"
	"usershop/api/internal/types"
	"usershop/api/pkg"
	"usershop/user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateByMobileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateByMobileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateByMobileLogic {
	return &UpdateByMobileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateByMobileLogic) UpdateByMobile(req *types.UpdatePasswordMobileRequest) (resp *types.ResMsg, err error) {
	// todo: 修改密码 By 手机号

	if !pkg.TelFormat(req.Mobile) {
		return &types.ResMsg{
			Cre:  -3,
			Msg:  "手机号格式错误",
			Data: nil,
		}, nil
	}

	//调用获取短信验证码接口
	_, err = l.svcCtx.UserSrv.GetSmsCode(l.ctx, &user.GetSmsCodeRequest{
		Mobile: req.Mobile,
		Source: "pwd",
	})
	if err != nil {
		return &types.ResMsg{
			Cre:  -2,
			Msg:  "服务器内部错误",
			Data: nil,
		}, nil
	}
	//获取盐 验证码 等...信息
	cc, err := l.svcCtx.UserSrv.UpdateByMobile(l.ctx, &user.UpdatePasswordMobileRequest{
		Mobile: req.Mobile,
	})

	fmt.Print("验证码..................." + cc.Code)

	if cc.Code != req.Code {
		return &types.ResMsg{
			Cre:  -4,
			Msg:  "验证码匹配错误",
			Data: nil,
		}, nil
	}

	//生成新盐
	salt := pkg.GenerateRandomstring(5) //盐
	fmt.Println("盐......", cc.Sale)
	md5 := pkg.Md5String(req.NewPassword + cc.Sale) //加密
	fmt.Println("加盐加密后的...................", md5)

	UserID := l.ctx.Value("UserID").(string) //获取中间件的token
	uin, _ := strconv.Atoi(UserID)           //转类型

	//修改密码
	_, err = l.svcCtx.UserSrv.UpdateByMobile(l.ctx, &user.UpdatePasswordMobileRequest{
		UserID:      int64(uin),
		NewPassword: md5,
		Sale:        salt,
	})
	if err != nil {
		return &types.ResMsg{
			Cre:  -3,
			Msg:  "修改失败",
			Data: nil,
		}, nil
	}

	return &types.ResMsg{
		Cre:  0,
		Msg:  "密码更新成功",
		Data: nil,
	}, nil
}
